<template>
  <div class="dashboard-container">
    <!-- 筛选查询 -->
    <el-form :inline="true">
      <el-form-item label="用户名">
        <el-input placeholder="请输入" v-model="params.nickName" clearable></el-input>
      </el-form-item>
      <el-form-item label="手机">
        <el-input placeholder="请输入" v-model="params.phone" clearable></el-input>
      </el-form-item>
      <el-button type="primary" @click="handleSearch">查询</el-button>
      <el-button type="primary" @click="handleAdd('create')">新增用户</el-button>
      <el-button type="primary" @click="handleUpload">批量导入</el-button>
      <el-button type="primary" @click="handleSelect">批量增加席位</el-button>
    </el-form>
    <div>
      <span>未使用席位数：</span>
      <span class="btn_number" v-for="item, index in pageList" :key="index">
        {{item.durationTypeName}}: {{item.packageCount}}个
      </span>
      <el-button type="primary" size="mini" @click="handlePay">购买席位</el-button>
      
    </div>
    <!-- 数据 -->
    <el-table :data="list" v-loading="loading" ref="multipleTable"  @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column type="index" label="序号"></el-table-column>
      <el-table-column prop="nickName" label="用户名"></el-table-column>
      <el-table-column prop="info" label="用户信息">
        <template slot-scope="{row}">
          {{ row.city.name }}
        </template>
      </el-table-column>
      <el-table-column prop="loginName" label="登录账号"></el-table-column>
      <el-table-column prop="phone" label="手机"></el-table-column>
      <el-table-column prop="sy" label="所属代理商">
        <template slot-scope="{row}">
          {{ row.parent.nickName }}
        </template>
      </el-table-column>
      <el-table-column prop="remainNoHarassCount" label="防投诉次数"></el-table-column>
      <el-table-column  label="防投诉到期时间">
        <template slot-scope="{row}">
          {{ row.time }}
        </template>
      </el-table-column>
      <el-table-column prop="remainOcrCount" label="ocr次数"></el-table-column>
      <el-table-column prop="remainSipCount" label="SIP"></el-table-column>
      <el-table-column prop="sy" label="状态">
        <template slot-scope="{row}">
          {{ row.enabled==1?"启用": "禁用" }}
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="注册时间"></el-table-column>
      <el-table-column  label="操作" width="200px">
        <template slot-scope="{row}">
          <el-button type="text" @click="handleAdd('update', row)">编辑</el-button>
          <el-button type="text" v-if="row.enabled==1" @click="handleEnable(row.id, 0)" style="color: red">停用</el-button>
          <el-button type="text" v-if="row.enabled==0" @click="handleEnable(row.id, 1)">启用</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div style="padding-top:30px; text-align: right;">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="params.pageIndex+1"
        background
        :page-sizes="[10, 20, 30, 40]"
        :page-size="params.pageCount"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>

    <!-- 新增、编辑 -->
    <el-dialog :title="dialogType=='create'?'新增用户':'编辑用户'" :visible.sync="dialogVisible" width="800px">
      <el-form label-width="100px" :model="temp"  :rules="rules" ref="ruleForm">
        <el-form-item label="用户名" prop="nickName">
          <el-input v-model="temp.nickName" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="登录账号" prop="loginName">
          <el-input v-model="temp.loginName" placeholder="请输入登录账号"></el-input>
        </el-form-item>
        <span style="color: red; height: 30px; line-height: 30px;padding-left: 100px;">登录账号、登录手机号二选一必填, 手机号也可进行密码登录</span>
        <el-form-item label="登录手机号" prop="phone">
          <el-input v-model="temp.phone" placeholder="请输入手机"></el-input>
        </el-form-item>
        
        <el-form-item label="密码" prop="password">
          <el-input v-model="temp.password " placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item label="城市" prop="cityId ">
          <el-select v-model="temp.cityId" placeholder="请选择" filterable @change="getCitys">
            <el-option
              v-for="item in cityList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div style="text-align: right;">
        <el-button @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')">确认</el-button>
      </div>
    </el-dialog>

    <!-- 批量导入用户 -->
    <el-dialog title="批量导入用户" :visible.sync="dialogVisibleUpload">
      <el-form label-width="100px" :model="tempUpload"  :rules="rulesUpload" ref="ruleFormUpload">
        <el-form-item label="导入文件" prop="fileName">
            <el-upload
                class="upload-demo"
                ref="upload"
                :action="BASE_URL+'/common/uploadLocalFile'"
                :on-remove="handleRemove"
                :on-success="handleSuccess"
                :file-list="fileList"
            >
                <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
                <div slot="tip" class="el-upload__tip">
                  只能上传excel文件，且不超过500kb
                  <a 
                    href="https://unicall.oss-cn-shanghai.aliyuncs.com/case/%E5%AF%BC%E5%85%A5%E7%94%A8%E6%88%B7.xlsx"
                    style="color: #409EFF;margin-left: 20px;"
                  >下载模板</a>
                </div>
            </el-upload>
        </el-form-item>
      </el-form>
      <div style="text-align: right;">
        <el-button @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="submitFormUpload('ruleFormUpload')">确认</el-button>
      </div>
    </el-dialog>

    <!-- 购买席位 -->
    <el-dialog title="购买席位"  :visible.sync="dialogVisiblePay" width="600px">
      <el-form label-width="100px" :model="tempPay"  :rules="rulesPay" ref="ruleFormPay">
        <el-form-item label="套餐" prop="menuId">
          <el-select v-model="tempPay.menuId" placeholder="请选择套餐" filterable  @change="handleChangePay">
            <el-option
              v-for="item in pageList"
              :key="item.id"
              :label="item.durationTypeName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数量" prop="menuCount"  >
          <el-input-number v-model="tempPay.menuCount" placeholder="请输入数量" @change="handleChangePay"></el-input-number>
        </el-form-item>
      </el-form>
      <div style="padding-left: 100px;">
        <span>价格：{{ payPrice}} 元</span>
        支付方式：支付宝
      </div>
      <div style="text-align: right;">
        <el-button @click="dialogVisiblePay=false">取消</el-button>
        <el-button type="primary" @click="submitFormPay('ruleFormPay')">确认</el-button>
      </div>
    </el-dialog>

    <!-- 分配席位 -->
    <el-dialog title="分配席位" :visible.sync="dialogVisibleSelect" width="600px">
      <el-form  :model="tempSelect"  :rules="rulesSelect" ref="ruleFormSelect">
        <div style="padding: 0 10px 20px 0">当前选择用户数：{{multipleSelection.length}} </div>
        <el-form-item label="套餐" prop="menuId">
          <el-select v-model="tempSelect.menuId" placeholder="请选择套餐" filterable @change="handleChangeSelect">
            <el-option
              v-for="item in pageList"
              :key="item.id"
              :label="item.durationTypeName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div style="padding: 0 10px 20px 0">当前该席位未使用数：{{userCount}} </div>
      <div style="text-align: right;">
        <el-button @click="dialogVisiblePay=false">取消</el-button>
        <el-button type="primary" @click="submitFormSelect('ruleFormSelect')">确认</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { userGetlist, userCreate, userEnable, userUpdate, userAdjustQuota, userImportList } from '@/api/user'
import { getProvinceList, getCityList } from "@/api/common";
import { BASE_URL, DURATION_TYPE_LIST } from '@/utils/common'
import { orderCreateMenuOrder, orderPay } from '@/api/order'
import { transfromData } from '@/utils/tools'
import { menuGetlist, menuAssignPackage } from '@/api/menu'
import moment from 'moment';
import md5 from 'js-md5'

export default {
  name: 'Dashboard',
  computed: {
    ...mapGetters([
      'name'
    ])
  },
  data(){
    return {
      BASE_URL,
      list: [],
      currentPage4: 1,
      params: {
        pageIndex: 0,
        pageCount: 10,
        role: 0,
        nickName: '',
        phone: ''
      },
      total: 0,
      value: '',
      options: [],
      loading: false,
      dialogType: 'create',
      dialogVisible: false,
      provinceList: [],
      cityList: [],
      temp: {},
      rules: {
        loginName: [{ min: 3, message: '长度至少3位', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
      },
      rulesUpload: {
        fileName: [{ required: true, message: '请上传文件', trigger: 'blur' }],
      },
      rulesPay: {
        menuCount: [{ required: true, message: '请填写数量', trigger: 'blur' }],
        menuId: [{ required: true, message: '请选择套餐', trigger: 'blur' }],
      },
      rulesSelect: {
        menuId: [{ required: true, message: '请选择套餐', trigger: 'blur' }],
      },
      dialogVisibleUpload: false,
      tempUpload: {},
      rulesNumber: {
        count: [{ required: true, message: '请输入数量', trigger: 'blur' }],
      },
      fileList: [],
      pageList: [],
      dialogVisiblePay: false,
      tempPay: {},
      multipleSelection: [],
      tempSelect: {
        count: 1,
        menuId: '',
        userIds: ''
      },
      dialogVisibleSelect: false,
      userCount: 0,
      payPrice: 0
    }
  },
  mounted(){
    //获取席位
    this.getMenu();
    //用户列表
    this.getList();
  },
  methods:{
    handleSearch(){
      this.params.pageIndex = 0;
      this.getMenu();
      this.getList();
    },
    handleChangeSelect(){
      let packageCount = this.pageList.filter(item=>item.id==this.tempSelect.menuId)[0].packageCount;
      this.userCount = packageCount
    },
    handleChangePay(){
      let price = this.pageList.filter(item=>item.id==this.tempPay.menuId)[0].price;
      this.payPrice = (price * this.tempPay.menuCount).toFixed(2)
    },
    //提交分配申请
    submitFormSelect(formName){
      this.$refs[formName].validate(async (valid) => {
          if (valid) {
            if(this.userCount<this.multipleSelection.length){
              this.$message.error({ message: '分配次数不足，请购买' })
              return;
            }
            //分配席位
            let data = await menuAssignPackage(this.tempSelect)
            this.$message.success({ message: '申请成功' })
            this.dialogVisibleSelect = false;
            this.getList();
            this.getMenu();
          } else {
            console.log('error submit!!');
            return false;
          }
        });
    },
    //点击批量增加席位
    handleSelect(){
      if(this.multipleSelection.length==0){
        this.$message.error({ message: '请选择用户' })
        return;
      }
      this.dialogVisibleSelect = true;
    },
    //选择监听事件
    handleSelectionChange(val) {
        this.multipleSelection = val;
        this.tempSelect.userIds = val.map(item=>item.id)
    },
    //提交支付
    submitFormPay(formName){
      this.$refs[formName].validate(async (valid) => {
          if (valid) {
            //充值下单
            let data = await orderCreateMenuOrder(this.tempPay)
            //订单支付
            let Pay = await orderPay({ orderId: data.data.id, payType: 1, returnPath: '' })
            // 表单数据 Pay.data.alipayTradeInfo
            let divForm = document.getElementsByTagName('payForm');
            if(divForm.length){
              document.body.remveChild(divForm[0])
            }
            const div = document.createElement('payForm');
            div.innerHTML = Pay.data.alipayTradeInfo;
            document.body.appendChild(div);
            document.forms['punchout_form'].setAttribute('target', '_blank')
            document.forms['punchout_form'].submit();
            
            this.dialogVisiblePay = false;
            //刷新套餐数量
            this.getMenu();
          } else {
            console.log('error submit!!');
            return false;
          }
        });
    },
    //点击购买
    handlePay(){
      this.tempPay = {
        menuCount: '',
        menuId: ''
      };
      this.dialogVisiblePay = true;
    },
    //获取席位配置
    async getMenu(){
      let data = await menuGetlist({style: 1, type: 0});
      this.pageList = data.data.map(item=>{
        item.durationTypeName = transfromData(DURATION_TYPE_LIST, item.durationType)
        item.price = item.price
        return item;
      })
    },
    //上传成功
    handleSuccess(response, file, fileList){
        this.tempUpload.fileName = response.data
    },
    // 移除
    handleRemove(file, fileList){
        this.tempUpload.fileName = ''
    },
    //点击批量上传用户
    handleUpload(){
      this.dialogVisibleUpload = true;
      this.tempUpload = { fileName: '' }
    },
    //获取城市列表
    async getCitys(){
      let data = await getCityList({ geoLevel: 2});
      this.cityList = data.data.map(item=>{
        return { label: item.name, value: item.id }
      })
    },
    //提交表单
    submitForm(formName){
      this.$refs[formName].validate(async (valid) => {
          if (valid) {
            let temp;
            temp = Object.assign({}, this.temp)
            if(temp.password){
              temp.password = md5(temp.password)
            }
            if(this.dialogType=='create'){
              await userCreate(temp)
            }else{
              await userUpdate(temp)
            }
            this.dialogVisible = false;
            this.getList();
          } else {
            console.log('error submit!!');
            return false;
          }
        });
    },

    // 批量导入提交表单
    submitFormUpload(formName){
      this.$refs[formName].validate(async (valid) => {
          if (valid) {
            let data = await userImportList(this.tempUpload)
            console.log()
            this.$message.success({ message: `成功导入${data.data}号码` })
            this.dialogVisibleUpload = false;
            this.getList();
          } else {
            console.log('error submit!!');
            return false;
          }
        });
    },
    //点击添加
    handleAdd(type, row){
      this.getCitys();
      this.dialogType = type;
      this.dialogVisible = true;
      if(type=='create'){
        this.temp = {
          loginName: '',
          password: '',
          phone: '',
          role: 0,
          cityId: ''
        }
      }else{
        row.password = '';
        row.dataId = row.id
        this.temp = Object.assign({}, row)
      }
    },
    //获取省列表
    async getProvince(){
      let data = await getProvinceList({ geoLevel: 1 });
      this.provinceList = data.data.map(item=>{
        return { label: item.name, value: item.id }
      })
    },
    //禁启用
    async handleEnable(id, enabled){
      await userEnable({ dataId: id, enabled });
      this.$message.success({ message: '操作成功' })
      this.getList();
    },
    //获取数据列表
    async getList(){
      this.loading = true;
      let data = await userGetlist(this.params) 
      this.loading = false;
      this.list = data.data.list.map(item=>{
        item.createTime = moment(item.createTime).format('YYYY-MM-DD HH:mm:ss')
        item.time = item.noHarassQuotaExpireTime==0?'':moment(item.noHarassQuotaExpireTime).format('YYYY-MM-DD')
        return item
      })
      this.total = data.data.totalCount;
    },
    //切换数量
    handleSizeChange(val){
      this.params.pageIndex = 0;
      this.params.pageCount = val;
      this.getList();
    },
    //切换页码
    handleCurrentChange(val){
      this.params.pageIndex = val-1;
      this.getList();
    }
  }
}
</script>

<style lang="scss" scoped>
.dashboard {
  &-container {
    margin: 30px;
    .btn_number{
      border: solid 1px #1e9fff;
      border-radius: 15px;
      color: #1e9fff;
      line-height: 30px;
      height: 30px;
      padding: 0 10px;
      display: inline-block;
      margin-right: 10px;
    }
  }
  &-text {
    font-size: 30px;
    line-height: 46px;
  }
}
</style>
